package com.cloud.es.controller;

import lombok.SneakyThrows;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

@RestController
@RequestMapping("/es/index")
public class EsIndexController {
    @Autowired
    private RestHighLevelClient client;

    // 创建索引
    @SneakyThrows
    @RequestMapping("/createIndex")
    public void createIndex() {
        Settings.Builder settingsBuilder = Settings.builder()
                .put("number_of_shards", 1)
                .put("number_of_replicas", 1);

        String mappingsJson = "{ \"properties\": { \"userName\": {\"type\": \"text\"}, \"age\": {\"type\": \"integer\"}, \"gender\": {\"type\": \"text\"} } }";

        CreateIndexRequest request = new CreateIndexRequest("user");
        if (settingsBuilder != null) {
            request.settings(settingsBuilder.build());
        }

        if (mappingsJson != null) {
            request.mapping(mappingsJson, XContentType.JSON); // _doc是7.x以后默认的文档类型
        }

        CreateIndexResponse response = client.indices().create(request, RequestOptions.DEFAULT);
        System.out.println("创建状态：" + response.isAcknowledged());
        client.close();//关闭资源
    }
    // 删除索引
    @RequestMapping("/deleteIndex")
    public void deleteIndex(String indexName) throws IOException {
        DeleteIndexRequest request = new DeleteIndexRequest("spring_test_log");

        AcknowledgedResponse response = client.indices().delete(request, RequestOptions.DEFAULT);

        if (response.isAcknowledged()) {
            System.out.println("索引 [" + "spring_test_log" + "] 已被删除");
        } else {
            System.out.println("索引 [" + "spring_test_log" + "] 删除请求未被确认");
        }
    }
    // 检验索引
    @RequestMapping("/checkIndex")
    public boolean indexExists(String indexName) throws IOException {
        GetIndexRequest request = new GetIndexRequest("spring_test_log");
        boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);
        return exists;
    }

}
